/**
 * 
 */
package com.designpattern.design.flyweight;

import java.util.HashMap;

/**
 * 享元模式练习
 * 
 * @author zhangyang
 *
 */
public class FlyWeightTest {

	public static void main(String[] args) {
		// 新闻发布一个系统 张三使用
		WebFactory webFactory = new WebFactory();
		WebSite webSite = webFactory.getWebSiteCategory("新闻");
		webSite.use(new User("张三"));
		WebSite webSite2 = webFactory.getWebSiteCategory("报纸");
		webSite2.use(new User("李四"));
		WebSite webSite3 = webFactory.getWebSiteCategory("报纸");
		webSite3.use(new User("王五"));
		WebSite webSite4 = webFactory.getWebSiteCategory("报纸");
		webSite4.use(new User("赵六"));
		System.out.println(webFactory.getConcreteSize());
		Integer a=127;
		Integer b=127;
		System.out.println(a==b);
		Integer c=128;
		Integer d=128;
		System.out.println(c==d);
		String str_1="1"+"2"+"3";
		String str_2="123";
		String str_3=new String("123");
		String intern = str_3.intern();
		System.out.println(str_1==str_2);
		System.out.println(str_2==str_3);
		System.out.println(str_2==intern);
	}
}

/**
 * 抽象享元对象
 * 
 * @author zhangyang
 *
 */
abstract class WebSite {
	public abstract void use(User user);
}

/**
 * 具体享元对象
 * 
 * @author zhangyang
 *
 */
class ConcreteWebSite extends WebSite {

	/**
	 * 发布方式-共享部分
	 */
	private String type;

	public ConcreteWebSite(String type) {
		super();
		this.type = type;
	}

	/**
	 * user就是用户，是享元模式非共享的部分
	 */
	@Override
	public void use(User user) {
		// TODO Auto-generated method stub
		System.out.println("当前网站发布方式是" + type + "正在使用人是:" + user.getName());
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

}

/**
 * 享元对象非共享属性
 * 
 * @author zhangyang
 *
 */
class User {
	private String name;

	public User(String name) {
		super();
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "User [name=" + name + "]";
	}

}

/**
 * 享元工厂 返回一个抽象的享元对象
 * 
 * @author zhangyang
 *
 */
class WebFactory {

	// 享元池，定义集合充当享元池的作用
	HashMap<String, ConcreteWebSite> pool = new HashMap<>();

	// 根据网站类型，返回一个对应的网站。如果没有就创建一个，放入池中并且返回
	public WebSite getWebSiteCategory(String type) {
		if (!pool.containsKey(type)) {
			// 如果没有就创建一个，放入池中
			pool.put(type, new ConcreteWebSite(type));
		}
		return pool.get(type);
	}

	public int getConcreteSize() {
		return pool.size();
	}
}